using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Deepcode.Flux.Core.Systems.Security;
using Deepcode.Flux.Core.Services.State;
using Deepcode.Flux.Core.Extensions;
using Deepcode.Flux.Core.Systems.Audit.Quick;

public partial class Private_Config_Users_ui_FormFormsAdd : Deepcode.Flux.Core.UI.AdministrationModulePage
{
	#region Permission Code Override
	public override string RequiredPermissionCode { get { return "FluxSecUsers"; } }
	#endregion
	#region ViewState storage
	/// <summary>
	/// Stores the state of the listing view
	/// </summary>
	public string ListingState
	{
		get
		{
			return (string)ViewState["ListingState"];
		}
		set
		{
			ViewState["ListingState"] = value;
		}
	}
	#endregion
	#region Page Load Event
	/// <summary>
	/// Page Load event
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void Page_Load(object sender, EventArgs e)
	{
		if (!Page.IsPostBack)
		{
			// Tell Email RE validator to use the email regex
			EmailRE.ValidationExpression = Deepcode.Flux.Core.Services.Assistant.Validations.EmailValidationExpression;

			// Store any state information from the calling listing
			this.ListingState = GetAttribute("state", "");

			// Setup the UI. 
			PopulateGroups();

			// Only other supers can set super flag
			if (!Deepcode.Flux.Core.Services.Security.AdministrationSecurity.IsSuperUser())
				extendedProperties.Visible = false;
		}
	}
	#endregion
	#region Page Init
	/// <summary>
	/// Initialisation - hook up events etc
	/// </summary>
	/// <param name="e"></param>
	protected override void OnInit(EventArgs e)
	{
		base.OnInit(e);
		EmailExists.ServerValidate += new ServerValidateEventHandler(ValidateEmailExists);
		PasswordMin5.ServerValidate += new ServerValidateEventHandler(ValidatePasswordMin5);
		PasswordsMatch.ServerValidate += new ServerValidateEventHandler(ValidatePasswordsMatch);
	}
	#endregion
	#region Navigation
	/// <summary>
	/// Returns to the listing, restoring state
	/// </summary>
	protected void GoBack()
	{
		string url = String.Format("listForms.aspx?state={0}", this.ListingState);
		Response.Redirect(url, true);
	}
	#endregion
	#region Save/Cancel handlers
	/// <summary>
	/// User cancelled the save, go back to previous page
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void btnCancel_Click(object sender, EventArgs e)
	{
		GoBack();
	}
	/// <summary>
	/// User clicked the save button, store the data
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void btnSave_Click(object sender, EventArgs e)
	{
		if (!Page.IsValid) return;
		AdministrationUsers users = new AdministrationUsers();
		AdministrationUser u = new AdministrationUser();

		// Create and save the user
		u.EMailAddress = this.EmailAddress.Text;
		u.RealName = this.RealName.Text;
		u.IsSuperUser = this.IsSuperUser.Checked;
		users.Save(u);
		
		// Set the user's password
		users.SetPassword( u.PK_ID, this.Password1.Text );
		
		// Set the user's groups
		int[] selectedIDs = Deepcode.Flux.Core.Services.Assistant.ControlUtil.GetListSelectedInts( this.UserGroups.Items );
		users.SetGroups(u.PK_ID, selectedIDs);

		QuickAudit.RaiseInformation(
			new AuditUser(),
			"Flux", "User manager",
			"created user {0} ({1} {2})",
			u.PK_ID, u.RealName, u.EMailAddress);
		
		GoBack();
	}
	#endregion
	#region Data functions for groups checklists
	/// <summary>
	/// Loads the groups checkbox list
	/// </summary>
	private void PopulateGroups()
	{
		AdministrationGroups GroupManager = new AdministrationGroups();
		AdministrationGroup[] groups = GroupManager.GetAllGroups();
		foreach (AdministrationGroup group in groups)
		{
			ListItem item = new ListItem();
			item.Value = group.PK_ID.ToString();
			item.Text = group.GroupName;
			this.UserGroups.Items.Add(item);
		}
	}
	#endregion
	#region Custom validators
	/// <summary>
	/// Ensures password is a minimum of 5 characters long.
	/// </summary>
	/// <param name="source"></param>
	/// <param name="args"></param>
	private void ValidatePasswordMin5(object source, ServerValidateEventArgs args)
	{
		if (args.Value.Length < 5) args.IsValid = false;
		else args.IsValid = true;
	}
	/// <summary>
	/// Ensures the two passwords match
	/// </summary>
	/// <param name="source"></param>
	/// <param name="args"></param>
	private void ValidatePasswordsMatch(object source, ServerValidateEventArgs args)
	{
		if (Password1.Text != Password2.Text) args.IsValid = false;
		else args.IsValid = true;
	}	
	/// <summary>
	/// Checks to ensure the email address isn't already registered
	/// </summary>
	/// <param name="source"></param>
	/// <param name="args"></param>
	private void ValidateEmailExists(object source, ServerValidateEventArgs args)
	{
		AdministrationUsers users = new AdministrationUsers();
		AdministrationUser u = users.GetUserByEmail(args.Value);
		if (u != null) args.IsValid = false;
		else args.IsValid = true;
	}
	#endregion
}
